package com.njrsrc.android.tasks;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;

import com.njrsrc.android.bean.UserInfo;
import com.njrsrc.common.utils.Helpers;
import com.njrsrc.common.utils.MsgID;

public class LoginTask extends AsyncTask<Object, Integer, Void> {
	private String url;
	private Handler loginHandler;
	private UserInfo loginInfo;

	@Override
	protected Void doInBackground(Object... params) {
		if (params.length < 3) {
			return null;
		}
		loginHandler = (Handler) params[0];
		url = (String) params[1];
		loginInfo = (UserInfo) params[2];
		JSONObject jsonObject = Helpers.getJSONArrayByGet(url);
		Message msg = loginHandler.obtainMessage();
		try {
			if(jsonObject == null)
			{
				msg.what = MsgID.LOGIN_ERROR;
			}
			else if (jsonObject.toString().contains("error_code")) {
				// 返回错误
				loginInfo.setError_code(jsonObject.getString("error_code"));
				loginInfo.setError_message(jsonObject.getString("error_message"));
				msg.what = MsgID.LOGIN_FAIL;
			} else {
				loginInfo.setUser_id(jsonObject.getString("user_id"));
				loginInfo.setToken(jsonObject.getString("token"));
				loginInfo.setResume_id(jsonObject.getString("resume_id"));
				msg.what = MsgID.LOGIN_SUCCESS;
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		loginHandler.sendMessage(msg);
		return null;
	}
}